package com.example.service.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.jwt.JWTUtil;
import com.example.client.StudentClient;
import com.example.client.TeacherClient;
import com.example.common.constent.JWTConstent;
import com.example.common.dto.LoginDto;
import com.example.common.vo.Result;
import com.example.entity.vo.LoginVo;
import com.example.entity.vo.RouterVo;
import com.example.service.pojo.Administrator;
import com.example.service.pojo.Router;
import com.example.service.service.AdministratorService;
import com.example.service.service.RouterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("system")
@RequiredArgsConstructor
@Tag(name = "系统管理")
public class LoginController {

    private final StringRedisTemplate stringRedisTemplate;

    private final StudentClient studentClient;

    private final TeacherClient teacherClient;

    private final AdministratorService administratorService;

    private final RouterService routerService;

    @PostMapping("login")
    @Operation(summary = "登录接口")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto){
        Result<Integer> login;
        List<Router> routerList = null;
        switch (loginDto.getIdentity()) {
            case "student" -> {
                login = studentClient.login(loginDto);
                routerList = routerService.lambdaQuery().eq(Router::getIdentity, "student").list();
                if(CollectionUtil.isEmpty(routerList)){
                    login = Result.serviceFail("student没有配置路由信息",null);
                }
            }
            case "teacher" -> {
                login = teacherClient.login(loginDto);
                routerList = routerService.lambdaQuery().eq(Router::getIdentity, "teacher").list();
                if(CollectionUtil.isEmpty(routerList)){
                    login = Result.serviceFail("teacher没有配置路由信息",null);
                }
            }
            case "admin" -> {
                Administrator administrator = administratorService.lambdaQuery()
                        .select(Administrator::getId)
                        .eq(Administrator::getNo, loginDto.getNo())
                        .eq(Administrator::getPassword, loginDto.getPassword())
                        .one();
                if(administrator==null){
                    login = Result.fail(JWTConstent.PASSWORD_ERROR_CODE,"账号或密码错误",null);
                }
                else {
                    login = Result.success(administrator.getId());
                }
                routerList = routerService.lambdaQuery().eq(Router::getIdentity, "admin").list();
                if(CollectionUtil.isEmpty(routerList)){
                    login = Result.serviceFail("admin没有配置路由信息",null);
                }
            }
            default -> {
                return Result.clientFail("未知角色", null);
            }
        }
        //如果登陆失败
        if(!(login.getCode()==Result.SUCCESS_CODE)){
            return Result.fail(login.getCode(),login.getMsg(),null);
        }
        //登陆成功
        Map<String,Object> payload = new HashMap<>();
        payload.put(JWTConstent.USER_ID,login.getData().toString());
        payload.put(JWTConstent.START_TIME,String.valueOf(System.currentTimeMillis()));
        //设置过期时间为30分钟
        payload.put(JWTConstent.EXPIRE_TIME,String.valueOf(System.currentTimeMillis()+ 1000L *60*JWTConstent.JWT_CONTINUE_TIME));
        String token = JWTUtil.createToken(payload, JWTConstent.JWT_KEY.getBytes());

        //构建loginVo
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        if(!CollectionUtil.isEmpty(routerList)) {
            List<RouterVo> routerVoList = routerList.stream().map(router -> {
                RouterVo routerVo = new RouterVo();
                BeanUtils.copyProperties(router, routerVo);
                return routerVo;
            }).collect(Collectors.toList());
            loginVo.setRouterInfo(routerVoList);
        }
        return Result.success(loginVo);
    }

}
